package cn.uikit.demo.location

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Intent
import android.content.pm.ServiceInfo
import android.location.LocationManager
import android.util.Log
import android.widget.RemoteViews
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationCompat.PRIORITY_MAX
import androidx.core.app.ServiceCompat
import androidx.core.location.GnssStatusCompat
import androidx.core.location.LocationManagerCompat
import androidx.lifecycle.LifecycleService
import cn.uikit.demo.R
import java.util.concurrent.Executor
import java.util.concurrent.Executors


class LocationService : LifecycleService() {

    companion object {
        private const val NOTIFICATION_CHANNEL_ID = "UIKit_LocationService"
        private const val NOTIFICATION_ID = 0x010
    }

    private val notificationManager by lazy {
        getSystemService(NotificationManager::class.java)
    }

    override fun onCreate() {
        super.onCreate()
        Log.d("Sivin", "LocationService onCreate: ")
        // 创建 MediaSession

    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        super.onStartCommand(intent, flags, startId)
        createChannel()
        showNotification()
        initLocation()

        return START_STICKY
    }

    private fun createChannel() {
        val importance = NotificationManager.IMPORTANCE_HIGH
        val channel = NotificationChannel(NOTIFICATION_CHANNEL_ID, "定位服务", importance)
        channel.description = "定位服务"
        notificationManager.createNotificationChannel(channel)
    }

    private fun updateNotification() {
        Thread {
            while (true) {
                showNotification()
                Thread.sleep(1000)
            }
        }.start()
    }

    private fun showNotification() {
        val notificationLayout = RemoteViews(packageName, R.layout.location_notification)
        notificationLayout.setTextViewText(R.id.title, "定位服务正在进行中")
        val intent = Intent(this, LocationTestActivity::class.java)
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
        val pendingIntent =
            PendingIntent.getActivity(
                this,
                0,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
            )
        val notification: Notification = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
            .setContentTitle("定位服务")
            .setContentIntent(pendingIntent)
            .setCustomContentView(notificationLayout)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentText("定位服务正在进行中...")
            .setCategory(NotificationCompat.CATEGORY_SERVICE)
            .setProgress(100, 20, true)
            .build()
        notification.flags = notification.flags or Notification.FLAG_ONGOING_EVENT
        ServiceCompat.startForeground(
            this,
            NOTIFICATION_ID,
            notification,
            ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION
        )
    }


    override fun onDestroy() {
        super.onDestroy()
        Log.d("Sivin", "LocationService onDestroy: ")
    }

    private val locationManager by lazy {
        getSystemService(LocationManager::class.java)
    }

    private val executor: Executor = Executors.newSingleThreadExecutor()


    private val gnssCallback = object : GnssStatusCompat.Callback() {
        override fun onStarted() {
            super.onStarted()
            Log.d("Sivin", "GNSS started: ")
        }

        override fun onStopped() {
            super.onStopped()
            Log.d("Sivin", "GNSS stopped: ")
        }

        override fun onFirstFix(ttffMillis: Int) {
            super.onFirstFix(ttffMillis)
            Log.d("Sivin", "First fix time: $ttffMillis ms")
        }

        override fun onSatelliteStatusChanged(status: GnssStatusCompat) {
            super.onSatelliteStatusChanged(status)
            Log.d("Sivin", "Number of satellites: ${status.satelliteCount}")
            var beidouCount = 0
            for (i in 0 until status.satelliteCount) {
                if (GnssStatusCompat.CONSTELLATION_BEIDOU == status.getConstellationType(i)) {
                    beidouCount += 1
                }
            }
            Log.d("Sivin", "北斗卫星: ${beidouCount}")
        }
    }

    @SuppressLint("MissingPermission")
    private fun initLocation() {
        val success = LocationManagerCompat.registerGnssStatusCallback(
            locationManager,
            executor,
            gnssCallback
        )
        Log.d("Sivin", "initLocation: $success")
        locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 1000L, 1.0f
        ) { location ->
            Log.d("Sivin", "经度：" + location.longitude + "，纬度：" + location.latitude)
        }
    }
}